<template>
  <div class="main-content-box">
    <div>
      <div id="container"></div>
      <!-- <div id="c1"></div>
      <div id="mountNode"></div>-->
    </div>
  </div>
</template>

<script>
import { Chart } from '@antv/g2';
import G6 from '@antv/g6';
export default {
  name: "chartsNodeTemplate",
  data () {
    return {
      orgData: {
        nodes: [
          {
            id: 'node0',
            x: 100,
            y: 100,
            label: 'Homepage',
            chartDatas: {
              type: 'ColumnChart',
              data: [
                { genre: 'Sports', sold: 275 },
                { genre: 'Strategy', sold: 115 },
                { genre: 'Action', sold: 120 },
                { genre: 'Shooter', sold: 350 },
                { genre: 'Other', sold: 150 }
              ],
              container: 'node0',
              size: {
                width: 300,
                height: 90
              }
            }
          },
          {
            id: 'node1',
            x: 300,
            y: 500,
            label: 'Subpage',
            chartDatas: {
              type: 'basicBar',
              container: 'node1',
              size: {
                width: 300,
                height: 90
              },
              data: [
                {
                  country: '巴西',
                  population: 18203
                }, {
                  country: '印尼',
                  population: 23489
                }, {
                  country: '美国',
                  population: 29034
                }, {
                  country: '印度',
                  population: 104970
                }, {
                  country: '中国',
                  population: 131744
                }
              ]
            }
          },
          {
            id: 'node2',
            x: 600,
            y: 250,
            label: 'SubOthers',
            chartDatas: {
              type: 'pieCharts',
              container: 'node2',
              size: {
                width: 300,
                height: 120
              },
              data: [
                { type: '一线城市', value: 0.19 },
                { type: '二线城市', value: 0.21 },
                { type: '三线城市', value: 0.27 },
                { type: '四线及以下', value: 0.33 },
              ]
            }
          },
        ],
        edges: [
          {
            source: 'node1',
            target: 'node2',
          },
          {
            source: 'node0',
            target: 'node2',
          },
        ],
      },
      currentGraph: null,
      basicBarChartProp: {

      },
      pieChartProp: {

      }
    }
  },
  methods: {
    test: function () {
      const data = this.basicColumnChartProp.data;
      // Step 1: 创建 Chart 对象
      const chart = new Chart({
        container: this.basicColumnChartProp.container, // 指定图表容器 ID
        width: this.basicColumnChartProp.width, // 指定图表宽度
        height: this.basicColumnChartProp.height // 指定图表高度
      });
      // Step 2: 载入数据源
      chart.data(data);
      // Step 3：创建图形语法，绘制柱状图，由 genre 和 sold 两个属性决定图形位置，genre 映射至 x 轴，sold 映射至 y 轴
      chart.interval().position('genre*sold').color('genre')
      // Step 4: 渲染图表
      chart.render();
    },
    basicBarChart: function () {
      let data = this.basicBarChartProp.data;
      let chart = new Chart({
        container: this.basicBarChartProp.container,
        width: this.basicBarChartProp.size.width,
        height: this.basicBarChartProp.size.height
      });
      chart.data(data);
      chart.axis('country', {
        label: {
          offset: 12
        }
      });
      chart.coordinate().transpose();
      chart.interval().position('country*population');
      chart.render();
    },
    initGraph () {
      let _that = this

      G6.registerNode('dom-node', {
        draw: (cfg, group) => {
          const stroke = cfg.style ? cfg.style.stroke || '#5B8FF9' : '#5B8FF9';
          const shape = group.addShape('dom', {
            name: 'dom-' + cfg.id,
            attrs: {
              width: cfg.size[0],
              height: cfg.size[1],
              html: `
              <div style="pading:5px;background-color:#999999;">             
                <div onclick="console.log('Hi')" ref=${cfg.id} id="${cfg.id}" class='dom-node' style="background-color: #fff; border: 2px solid ${stroke}; border-radius: 5px; width: ${cfg.size[0] - 5}px; height: ${cfg.size[1] - 25}px; padding-top:5px;"></div>
                <div style="margin:auto; padding:auto; color: cyan">${cfg.label} </div>
              </div>        
          `
            },
            draggable: true
          });
          return shape;
        }
      });

      const width = document.getElementById('container').scrollWidth;
      const height = document.getElementById('container').scrollHeight || 800;
      const graph = new G6.Graph({
        container: 'container',
        width,
        height,
        modes: {
          // default: ['drag-canvas', 'drag-node'],  // 需要屏蔽事件交互，否则节点中的charts图表的canvas会被删除
        },
        // translate the graph to align the canvas's center, support by v3.5.1
        // fitCenter: true,
        renderer: 'svg',
        // linkCenter: true,
        defaultNode: {
          type: 'dom-node',
          size: [400, 150]
        }
      });

      graph.data(_that.orgData);
      graph.render();
      graph.get('canvas').set('localRefresh', false)

      _that.currentGraph = graph


    },
    initCharts () {
      let forLength = this.orgData.nodes.length
      for (let i = 0; i < forLength; i++) {
        const data = this.orgData.nodes[i].chartDatas.data;
        // Step 1: 创建 Chart 对象
        const chart = new Chart({
          container: this.orgData.nodes[i].chartDatas.container, // 指定图表容器 ID
          width: this.orgData.nodes[i].chartDatas.size.width, // 指定图表宽度
          height: this.orgData.nodes[i].chartDatas.size.height // 指定图表高度
        });
        // Step 2: 载入数据源
        chart.data(data);

        // Step 3：创建图形语法，绘制柱状图，由 genre 和 sold 两个属性决定图形位置，genre 映射至 x 轴，sold 映射至 y 轴
        let chartsType = this.orgData.nodes[i].chartDatas.type
        switch (chartsType) {
          case 'ColumnChart':
            chart.interval().position('genre*sold').color('genre')
            break;
          case 'basicBar':
            chart.axis('country', {
              label: {
                offset: 12
              }
            });
            chart.coordinate().transpose();
            chart.interval().position('country*population');
            break;
          case 'pieCharts':
            chart.legend(false);
            chart.coordinate('theta', {
              radius: 0.75,
              innerRadius: 0.4
            });
            chart.tooltip({
              showMarkers: false
            });

            const interval = chart
              .interval()
              .adjust('stack')
              .position('value')
              .color('type', ['#063d8a', '#1770d6', '#47abfc', '#38c060'])
              .style({ opacity: 0.4 })
              .state({
                active: {
                  style: (element) => {
                    const shape = element.shape;
                    return {
                      matrix: Util.zoom(shape, 1.1),
                    }
                  }
                }
              })
              .label('type', (val) => {
                const opacity = val === '四线及以下' ? 1 : 0.5;
                return {
                  offset: -30,
                  style: {
                    opacity,
                    fill: 'white',
                    fontSize: 12,
                    shadowBlur: 2,
                    shadowColor: 'rgba(0, 0, 0, .45)',
                  },
                  content: (obj) => {
                    return obj.type + '\n' + obj.value + '%';
                  },
                };
              });

            chart.interaction('legend-active');
            break;

        }
        // Step 4: 渲染图表
        chart.render();
      }
    }
  },
  mounted () {
    // console.log(Chart)
    this.initGraph()
    setTimeout(() => {
      this.$nextTick(() => {
        this.initCharts()
      })
    }, 10)
    // this.test();
    // this.basicBarChart();
  },
  beforeCreate () {
    document.querySelector('body').setAttribute('style', 'background:#ffffff')
  },
  beforeDestroy () {
    document.querySelector('body').removeAttribute('style')
  }
}
</script>

<style scoped>
.main-content-box {
  width: 95%;
  margin: 5px 20px;
}
.demoDiv {
  position: relative;
  padding: 20px;
  border: 1px solid skyblue;
}
.toolDiv {
  width: 50px;
  border: 1px solid #f5f5f5;
  position: absolute;
  z-index: 100;
}
.tool_area {
  position: absolute;
  top: 0;
  right: 0;
}
</style>